<?php
class Goodsbase extends CS_Controller
{
    private $machineUser = array();
    private $providerUser = array();
    private $postData = array();

    public function _init()
    {
        $this->load->helper(array('common','api'));
        $this->load->library('pagination');
        $this->load->model('goods_base_model', 'goods_base');
        $this->load->model('scenery_base_model', 'scenery_base');
        $this->load->model('user_type_model', 'user_type');
        $this->load->model('region_model', 'region');
        $this->load->model('scenery_good_category_model', 'scenery_good_category');
        $this->load->model('api_if_model', 'api_if');
        $this->load->model('user_model', 'user');
        $this->load->model('goods_map_profit_model', 'goods_map_profit');
        $this->load->model('scenery_good_category_model', 'scenery_good_category');
        $this->load->model('goods_macs_model', 'goods_macs');
        $this->load->model('goods_category_model', 'goods_category');
        $this->load->model('goods_map_cpt_model', 'goods_map_cpt');
        $this->load->model('operate_power_log_model', 'operate_power_log');
    }

    public function index($pg = 1)
    {
        $getData = $this->input->get();
        if (isset($getData['excel']) && $getData['excel']== 'excel') {
            $this->excelExport($getData);
        } else {
            $page_num = 20;
            $num = ($pg - 1) * $page_num;
            $config['first_url'] = base_url('goodsbase/index').$this->pageGetParam($this->input->get());
            $config['suffix'] = $this->pageGetParam($this->input->get());
            $config['base_url'] = base_url('goodsbase/index');
            $config['total_rows'] = $this->goods_base->total($this->input->get());
            $config['uri_segment'] = 3;
            $this->pagination->initialize($config);
            $data['pg_list'] = $this->pagination->create_links();
            $data['page_list'] = $this->goods_base->page_list($page_num, $num, $this->input->get());
            $data['all_rows'] = $config['total_rows'];
            $data['pg_now'] = $pg;
            $data['bit_source'] = $this->scenery_good_category->find(true);
            $data['cat_id'] = $this->goods_category->find(true);
            $data['is_check'] = array(1=>'待审核', 2=>'审核通过', 3=>'审核失败');
            $data['bit_opt'] = array(4=>'付款后分润', 8=>'使用后分润', 16=>'刷身份证', 32=>'核对身份证', 1024=>'系统结算', 2048=>'自主结算', 4096=>'日常票', 8192=>'周末票', 16384=>'座位票');
            $this->load->view('goodsbase/index', $data);
        }
    }

    public function add()
    {
        $sid = $this->input->get('sid');
        $result = $this->scenery_base->findById($sid);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '景区信息不存在');
        }
        $scenery = $result->row();
        $result1 = $this->user->findById($scenery->uid);
        if ($result1->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '供应商信息错误或不存在');
        }
        $data['user'] = $result1->row();
        $data['cat_id'] = $this->goods_category->find(true);
        $data['userType'] = $this->user_type->get_list();
        $data['bit_source'] = $this->scenery_good_category->find(true);
        $data['api_if'] = $this->api_if->find();
        $data['is_check'] = array(1=>'待审核', 2=>'审核通过', 3=>'审核失败');
        $data['is_refund'] = array(1=>'可退',2=>'不可退');
        $data['is_edit'] = array(1=>'可改',2=>'不可改');
        $data['sfz_booking_limit'] = array(0=>'无',1=>'1天',2=>'1周',3=>'1月',4=>'1年');
        $this->load->view('goodsbase/add', $data);
    }
    
    public function ajaxValidate()
    {
        $error = $this->validate();
        if (!empty($error)) {
            $this->jsonMessage($error);
        }
        $error = $this->validateProfit();
        if (!empty($error)) {
            $this->jsonMessage($error);
        }
        $this->getBitOpt();
        if ($this->input->post('goods_id')) {
            $this->editPost();
        } else {
            $this->addPost();
        }
    }
    
    public function addPost()
    {
        $this->db->trans_start();
        $goodsId = $this->goods_base->insertGoodsBase($this->postData);
        $profitId = $this->goods_map_profit->insertGoodsMapProfit($this->postData, $goodsId);//分润添加
        $result = $this->user->findByParentIds($this->providerUser);
        if ($result->num_rows() > 0) {
            $bit_cpt = 1;
            foreach ($result->result() as $item) {
                if ((int)$item->user_type&UTID_TELLER) {
                    $params = array('goods_id'=>$goodsId, 'uid'=>$item->uid, 'bit_cpt'=>$bit_cpt);
                    $this->goods_map_cpt->insertGoodsMapCpt($params);
                    $bit_cpt = $bit_cpt*2;
                }
            }
        }
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->postData)));
        $this->db->trans_complete();
        if ($this->db->trans_status() === TRUE && $goodsId && $profitId) {
            $this->session->set_flashdata('success', '保存成功！');
            $this->jsonMessage('', base_url('goodsbase/index?sid=' . $this->input->post('sid')));
        } else {
            $this->session->set_flashdata('error', '保存失败！');
            $this->jsonMessage('', base_url('goodsbase/index?sid=' . $this->input->post('sid')));
        }
    }

    public function edit($goods_id)
    {
        $result = $this->goods_base->findById($goods_id);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '供应商信息错误或不存在');
        }
        $goodsBase = $result->row();
        $data['goodsBase'] = $goodsBase;
        $result = $this->scenery_base->findById($goodsBase->sid);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '景区信息不存在');
        }
        $data['scenery'] = $result->row();;
        $data['cat_id'] = $this->goods_category->find(true);
        $data['userType'] = $this->user_type->get_list();
        $data['bit_source'] = $this->scenery_good_category->find(true);
        $data['api_if'] = $this->api_if->find();
        $data['profit'] = $this->goods_map_profit->findByGoodsId($goods_id);
        $data['is_check'] = array(1=>'待审核', 2=>'审核通过', 3=>'审核失败');
        $data['is_refund'] = array(1=>'可退',2=>'不可退');
        $data['is_edit'] = array(1=>'可改',2=>'不可改');
        $data['sfz_booking_limit'] = array(0=>'无',1=>'1天',2=>'1周',3=>'1月',4=>'1年');
        $this->load->view('goodsbase/edit', $data);
    }
    
    public function copy($goods_id)
    {
        $result = $this->goods_base->findById($goods_id);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '供应商信息错误或不存在');
        }
        $goodsBase = $result->row();
        $data['goodsBase'] = $goodsBase;
        $result = $this->scenery_base->findById($goodsBase->sid);
        if ($result->num_rows() <= 0) {
            $this->error('goodsbase/index', $this->input->get(), '景区信息不存在');
        }
        $data['scenery'] = $result->row();;
        $data['cat_id'] = $this->goods_category->find(true);
        $data['userType'] = $this->user_type->get_list();
        $data['bit_source'] = $this->scenery_good_category->find(true);
        $data['api_if'] = $this->api_if->find();
        $data['profit'] = $this->goods_map_profit->findByGoodsId($goods_id);
        $data['is_check'] = array(1=>'待审核', 2=>'审核通过', 3=>'审核失败');
        $data['is_refund'] = array(1=>'可退',2=>'不可退');
        $data['is_edit'] = array(1=>'可改',2=>'不可改');
        $data['sfz_booking_limit'] = array(0=>'无',1=>'1天',2=>'1周',3=>'1月',4=>'1年');
        $this->load->view('goodsbase/copy', $data);
    }
    
    public function editPost()
    {
        $goodsId = $this->input->post('goods_id');
        $this->db->trans_start();
        $update = $this->goods_base->updateGoodsBase($this->postData);
        $is_delete = $this->goods_map_profit->delete($goodsId);
        $profitId = $this->goods_map_profit->insertGoodsMapProfit($this->postData, $goodsId);//分润添加
        $result = $this->user->findByParentIds($this->providerUser);
        if ($result->num_rows() > 0) {
            foreach ($result->result() as $item) {
                if ((int)$item->user_type&UTID_TELLER) {
                    $goodsMapCpt = $this->goods_map_cpt->findGoodsMapCpt(array('goods_id'=>$goodsId, 'uid'=>$item->uid));
                    if ($goodsMapCpt->num_rows() == 1) {
                        continue;
                    }
                    $newMapCpt = $this->goods_map_cpt->findGoodsMapCpt(array('goods_id'=>$goodsId, 'limit'=>1));
                    if ($newMapCpt->num_rows() <= 0) {
                        $bit_cpt = 1;
                    } else {
                        $bit_cpt = ($newMapCpt->row(0)->bit_cpt)*2;
                    }
                    $params = array('goods_id'=>$goodsId, 'uid'=>$item->uid, 'bit_cpt'=>$bit_cpt);
                    $this->goods_map_cpt->insertGoodsMapCpt($params);
                }
            }
        }
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->postData)));
        $this->db->trans_complete();
        if ($this->db->trans_status() === TRUE && $update && $is_delete && $profitId) {
            $this->session->set_flashdata('success', '保存成功！');
            $this->sendProductChangedInfo($goodsId, 2);//发送产品变化通知给合作平台（20160510由叶青芽添加）
            $this->jsonMessage('', base_url('goodsbase/index?sid=' . $this->input->post('sid')));
        } else {
            $this->session->set_flashdata('error', '保存失败！');
            $this->jsonMessage('', base_url('goodsbase/index?sid=' . $this->input->post('sid')));
        }
    }

    public function getBitOpt()
    {
        $bit_line = $this->input->post('bit_line');
        $bit_profit = $this->input->post('bit_profit');
        $bit_sfz = $this->input->post('bit_sfz');
        $bit_offer = $this->input->post('bit_offer');
        $bit_js = $this->input->post('bit_js');
        $bit_seat = $this->input->post('bit_seat');
        $bit_week = $this->input->post('bit_week');
        $bit_zf = $this->input->post('bit_zf');

        $bit_pay = 0;
        foreach ($bit_zf as $value) {
            $bit_pay += $value;
        }

        $bit_opt = $bit_line + $bit_profit + $bit_sfz + $bit_offer + $bit_js + $bit_seat + $bit_week + $bit_pay;

        $this->postData = $this->input->post();
        $this->postData['bit_opt'] = $bit_opt;
        $this->postData['status'] = 'profit';
    }
    
    //审核状态
    public function isCheck()
    {
        $goodsId = $this->input->post('goods_id');
        $isCheck = $this->input->post('is_check');
        $update = $this->goods_base->updateParams(array('goods_id' => $goodsId, 'is_check' => $isCheck));
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->input->post())));
        if ($update) {
            echo json_encode(array(
                'status' => true,
            ));exit; 
        }
    }
    
    //上下架
    public function toggle()
    {
        $goodsId = $this->input->post('goodsId');
        $bitopt = $this->input->post('bitopt');
        $flag = 0;

        if (intval($bitopt & 2) == 2) {
            $bitopt = $bitopt - 1;
            $flag = 1;
            $status = 1;//产品上架
        } elseif (intval($bitopt & 1) == 1) {
            $bitopt = $bitopt + 1;
            $flag = 2;
            $status = 0;//产品下架
        }
        $this->operate_power_log->insertOperatePowerLog(array('uid'=>$this->uid,'name'=>$this->name,'record'=>'操作类：'.__CLASS__.'-方法：'.__FUNCTION__, 'content'=>json_encode($this->input->post())));
        $update = $this->goods_base->updateParams(array('goods_id' => $goodsId, 'bit_opt' => $bitopt));
        if ($update) {
            echo json_encode(array('status' => $flag, 'bitopt' => $bitopt));
            $this->sendProductChangedInfo($goodsId, $status);//发送产品变化通知给合作平台（20160510由叶青芽添加）
            exit;
        }
    }

    public function validate()
    {
        $error = array();
        if ($this->validateParam($this->input->post('goods_name'))) {
            $error[] = '门票名称不可为空！';
        }
        if ($this->validateParam($this->input->post('bit_zf'))) {
            $error[] = '支付方式不可为空！';
        }
        if ($this->input->post('sell_end_time') < $this->input->post('sell_start_time')) {
            $error[] = '下架时间必须要大于上架时间。';
        }
        if (!is_numeric($this->input->post('market_price'))) {
            $error[] = '市场价格只能为数字。';
        }
        if (!is_numeric($this->input->post('shop_price'))) {
            $error[] = '着想价只能为数字。';
        }
        if (!is_numeric($this->input->post('provide_price'))) {
            $error[] = '供应价只能为数字。';
        }
        return $error;
    }

    public function validateProfit()
    {
        $error = array();

        $typeIDArray = $this->input->post('type_id');
        $uidArray = $this->input->post('uid');
        $amountArray = $this->input->post('amount');

        $amount = 0;        //分销商总金额
        $amountUid = 0;     //供应商总金额
        $flag = 0;          //判断是否有供应商
        $purchaserNum = 0;  //判断是采购商个数
        if (empty($uidArray) || empty($typeIDArray) || empty($amountArray)) {
            return $error[] = '请填写分润信息！';
        }

        if (count($uidArray) != count($typeIDArray) || count($uidArray) != count($amountArray)) {
            return $error[] = '请将分润信息填写完整';
        }
        
        foreach ($typeIDArray as $key => $value) {
            $typeID = (int)$value;
            if ($typeID == UTID_PROVIDER || $typeID == UTID_PROSECOND) {
                $amountUid += $amountArray[$key];
                $this->providerUser[] = $uidArray[$key];
            } else {
                if ($typeID == UTID_PURCHASER) {
                    $purchaserNum += 1;
                }
            }
            if ($typeID != UTID_ACTUAL && $typeID != UTID_BONUSES) { //实际支付款项 和 游币
                $amount += $amountArray[$key];
            }
        }
        
        if (bccomp($amountUid, $this->input->post('provide_price'), 3) != 0) {
            return $error[] = '供应商加二级供应总金额' . $amountUid . '与供应价' . $this->input->post('provide_price') . '不符！';
        }
        if (bccomp($amount, $this->input->post('shop_price'), 3) != 0) {
            return $error[] = '总金额' . $amount . '与着想价格' . $this->input->post('shop_price') . '不符！';
        }
        
        //去掉为空  的用户uid
        foreach ($uidArray as $key => $value) {
            if (empty($value)) {
                unset($uidArray[$key]);
            }
        }

        $result = $this->user->findByIds(array('uid' => $uidArray));
        if (empty($result)) {
            return $error[] = '用户编号为' . implode(array_flip($uidArray), ',') . '的用户不存在';
        }
        $uidArray = array_flip($uidArray);   //  key值交换

        foreach ($result->result() as $value) {
            if (in_array($value->uid, $this->providerUser)) {
                $flag += 1;
            }
            if (array_key_exists($value->uid, $uidArray)) {
                unset($uidArray[$value->uid]);
            }
        }
        if ($flag == 0) {
            return $error[] = '请填写真实的供应商或二级供应商';
        } else {
            $resultUid = $this->scenery_base->findById($this->input->post('sid'));
            $supplier = $resultUid->row();
            if (!in_array($supplier->uid, $this->providerUser)) {
                return $error[] = 'UID'.implode(',', $this->providerUser).'不存在该供应商（' . $supplier->uid . '），请仔细核实。';
            }
        }

        if (!empty($uidArray)) {
            return $error[] = '用户UID为' . implode(array_flip($uidArray), ',') . '的账号不存在';
        }
        return $error;
    }
    
    //发送产品变化通知给合作平台
    private function sendProductChangedInfo($goods_id, $status)
    {
        $data = "goods_id=".$goods_id."&status=".$status;
        $http = $this->config->api_base_url.'bzApi/productNotice';
        getApiDynamic($data,$http);
    }
    
    public function excelExport($getData)
    {
        $result = $this->goods_base->excelExport($getData);
        if($result->num_rows() <= 0){
            $this->error('goodsbase/index', null, '这个时间段没有记录');
        }
        if($result->num_rows() > 10000){
            $this->error('goodsbase/index', null, '由于导出的数据太多，请选择一个时间范围');
        }
        $arrayGoods = $result->result_array();
    
        array_unshift($arrayGoods, array('景区编号', '门票编号', '票种编号' , '门票名称', '供应商', '供应商别名', '销售价', '供应价', '票种来源', '接口编号', '有效期开始', '有效期结束'));
        $this->load->library('excel');
        $this->excel->addArray($arrayGoods);
        $this->excel->generateXML(date('Ymd').'门票列表');
    }
}